import java.util.LinkedList;
import java.util.Queue;

class Solution {

    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };
    public Node connect(Node root) {

        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int levelSize = queue.size();
            Node head;
            for (int i = 0; i < levelSize; i++) {
                head = queue.poll();
                if(i == levelSize - 1){
                    head.next = null;
                }
                else{
                    head.next = queue.peek();
                }
                if(head.left != null){
                    queue.add(head.left);
                }
                if(head.right != null){
                    queue.add(head.right);
                }
            }
        }
        return root;
    }
}
